 
#!/usr/bin/python
#coding:utf-8 
# from Util.jarProjectUtil import JarProjectUtil  
# # from Doc.ApiDoc2 import app  

# # Todo 主程序启动页面
# if __name__=='__main__': 
#     pathUtil=JarProjectUtil().author()
#     print(pathUtil)
#     # app


# #todo  运行设置
# # 再根目录 导出 pipreqs ./ --encoding=utf8
# #pip3 install -r requirements.txt # 安装


import os
from flask import Flask,jsonify,request,Response
from Util.jarProjectUtil import JarProjectUtil
from werkzeug.utils import secure_filename
from Commons.filePath import FilePath
from Controller.ImgController import ImgController
from Config.Config import Config  

from flask_cors import CORS

imgconfig=Config().imgConfig() 
appsetting=Config().appSetting()
author=JarProjectUtil().author()
imgSavePath=FilePath("/static/common/").path()
bgimgPath=FilePath("/static/bgimg/").path()
maskimgPath=FilePath("/static/maskimg/").path() 

# 控制器
width=imgconfig["width"]
height=imgconfig["height"]  
smallwidth=imgconfig["smallwidth"]
smallheight=imgconfig["smallheight"]  
sde=ImgController(bgimgPath,maskimgPath,imgSavePath,height=height,width=width,smallwidth=smallwidth,smallheight=smallheight,imgurl=appsetting["url"])  
app=Flask(__name__,static_folder='static/common')

# r'/*' 是通配符，让本服务器所有的URL 都允许跨域请求
# CORS(app, resources=r'/*')
# 运行哪些域名可以跨域访问
cors = CORS(app, resources={r"/.*": {"origins": appsetting["origins"]}})  
@app.route("/captcha/hello",methods=["GET"])
def hello():
    args = request.args.get("token") or None
    if(args==None):
        return jsonify(  
             {"api":None,
             "code":200,
            "result":False  ,
            "msg":"参数不合法"
             })
    if args not in appsetting["token"]:
        return jsonify(
            {"api":None,
             "code":200,
            "result":False  ,
            "msg":"未授权请求"
             } 
        )
    return jsonify(
        {"api":{"msg":"Hello World!"},
         "code":200,
            "msg":"",
         "result":True 
        }
    )
    


@app.route("/captcha/checkData",methods=["POST"])
def checkData():
    """ 将接收的数据进行解密验证 
    ### 参数
    |  args | nullable | request type | type |  remarks |
    |-------|----------|--------------|------|----------|
    | token |  false   |    body      | str  | 数据加密返回   |
    | timestamp  |  false   |    body      | str  |  时间戳  |
    ### 请求
    ```json
    {"token": "tokentokentokentokentokentokentoken", "timestamp": "24233333353535435"}
    ```
    ### 响应
    ```json
    {"code": 200,"result":true, "msg": "", "data": null}
    {"code": 200,"result":false, "msg": "验证失败", "data": null}
    {"code": 200,"result":false, "msg": "参数不能为空", "data": null}
    {"code": 200,"result":false, "msg": "请稍候再试", "data": null}
    ``` 
    """
    if request.method == 'GET': 
        return jsonify({"code": 200,"result":False, "msg": "请求方式错误", "data": None})
    token = request.form.get("token")
    timestamp = request.form.get("timestamp")
    if(not timestamp or not token): 
        return jsonify({"code": 200,"result":False, "msg": "参数不能为空", "data": None})
        # 这里需要用到redis 去判断这个key值是否等于 ,我这里没有处理了
        # 因为Python 这里 没怎么处理过连接,我直接在项目内请求加密返回base64 图片流
        # python的作用就是生成验证码, 返回 坐标轴
        #时间戳 就是为了验证是否 正确
    return jsonify({"api":request.form,"msg":"测试post"})


@app.route("/captcha/get",methods=["GET"])
def getCapycha():
    """获取验证码图片  
    ```json
    {"code": 200,"result":true ,"msg": "", "data": {
        bg:"helloworld.png",
        gapDiagram:"gapdiagram.png",
        token:"sfsfwkjriowrwrjlwuisw",加密x,y 轴数据 
    }}
    {"code": 200,"result":false, "msg": "您验证次数过多,请重新尝试,在1秒钟刷新过多次", "data": {
        bg:"",
        gapDiagram:"",
        token:"wrwerwrwerwrwe" 无效的token 
    }}
    {"code": 500,"result":false, "msg": "请稍候再试", "data":  {
        bg:"",
        gapDiagram:"",
        token:"wrwerwrwerwrwe" 无效的token 
    }}
    ``` 
    """
    args = request.args.get("token") or None
    if(args==None):
        return jsonify(  
             {"api":None,
             "code":200,
            "result":False  ,
            "msg":"参数不合法"
             })
    if args not in appsetting["token"]:
        return jsonify(
            {"api":None,
             "code":200,
            "result":False  ,
            "msg":"未授权请求"
             } 
        )
    captcha= sde.getinfo()
    print("当前验证码信息\n  X:{0} \nY:{1} \ntimestamp :{2} \ninfo: {3}".format(captcha["x"],captcha["y"],captcha["timestamp"],captcha["info"]))
    return jsonify(
            {"api":captcha,
             "code":200,
            "result":True  ,
            "msg":""
             }
    
    )


@app.route("/captcha/refresh",methods=["GET"])
def getrefresh():
    """刷新验证码图片  """
    args = request.args.get("token") or None
    if(args==None):
        return jsonify(  
             {"api":None,
             "code":200,
            "result":False  ,
            "msg":"参数不合法"
             })
    if args not in appsetting["token"]:
        return jsonify(
            {"api":None,
             "code":200,
            "result":False  ,
            "msg":"未授权请求"
             } 
        )
    sde.CaptchaBgImg()
    sde.CgetGapDiagramImg()
    captcha= sde.getinfo() 
    print("X:{0} \nY:{1}\ntimestamp :{2} \ninfo: {3}".format(captcha["x"],captcha["y"],captcha["timestamp"],captcha["info"]))
    return jsonify({"api": captcha,
            "msg":"",
             "code":200,
            "result":True  
    })


@app.route("/captcha/deletecache",methods=["POST"])
def deletecache():
    if request.method == 'GET': 
        return jsonify({"code": 200,"result":False, "msg": "请求方式错误", "data": None})
    token = request.form.to_dict() 
    if token["token"] not in appsetting["authtoken"]:
        return jsonify(
            {"api":None,
             "code":200,
            "result":False  ,
            "msg":"未授权请求"
             } 
        )

    try:
        isok=sde.deleteimg()
        msg="操作成功"
    except  :
        isok=False
        msg="操作失败"

    return jsonify(   
            {"api":None,
             "code":200,
            "result":isok  ,
            "msg":msg
             })


# 查看图片
@app.route("/captcha/img/<imageId>",methods=["GET"])
def get_frame(imageId):
    args = request.args.get("token") or None
    if(args==None):
        return jsonify(  
             {"api":None,
             "code":200,
            "result":False  ,
            "msg":"参数不合法"
             })
    if args not in appsetting["token"]:
        return jsonify(
            {"api":None,
             "code":200,
            "result":False  ,
            "msg":"未授权请求"
             } 
        )
    # 图片上传保存的路径
    try:
        with open(imgSavePath+"{}".format(imageId), 'rb') as f:
            image = f.read()
            resp = Response(image, mimetype="image/jpg")
            print(imgSavePath+"{}".format(imageId))
            return resp
    except:  
        return jsonify(
            {"api":None,
             "code":200,
            "result":False  ,
            "msg":"图片已经过期,请刷新您的页面"
             } 
        )
        #os.remove(imgSavePath+"{}".format(imageId)) 


# 设置上传图片大小一致
# @app.route("/captcha/set",methods=["GET"])
# def imgset():
#     sde.imgcompress()
#     return jsonify({"api": "ok"})



# @app.route("/update/file",methods=["POST"])
# def uploadImg():
#     """
#         验证码图片上传
#         @@@
#         ### description
#         > 上传图片
#         ### args
#         |  args | nullable | request type | type |  remarks |
#         |-------|----------|--------------|------|----------|
#         |  pathimage |  false   |    body      | image  | 图片 |
#         |  timestamp |  false   |    body      | string  | 上传时间戳(毫秒级) |
#         ### request
#         ```json
#         {"pathimage": "bitter", "timestamp": "139472874782323"}
#         ```
#         ### return
#         ```json
#         {"code": 200,"status":true, "msg": "上传成功", "data": null}
#         {"code": 200,"status":false,"msg": "上传失败", "data": null}
#         ```
#         @@@
#     """


#     if request.method == 'POST':
#     # 获取post过来的文件名称，从name=file参数中获取

#         print(request.files,"info")
    
#         print(request.form,"时间戳")

#         return jsonify({"code": 200,"status":True, "msg": "上传成功", "data": None})

#         print(timestamp,"时间戳")
#         print(file)
#         # secure_filename方法会去掉文件名中的中文
#         file_name = secure_filename(file.filename)
#       # 保存图片
#         file_path = bgimgPath+timestamp
#         # file.save(file_path) 


#     # img = request.files.get('pathimage')
#     # timestamp = request.form.get("timestamp")
#     # if img ==None:
#     #     return  jsonify({"code": 200,"status":False,"msg": "图片必填", "data": None})
    
#     # if timestamp ==None:
#     #     return  jsonify({"code": 200,"status":False,"msg": "时间戳必填", "data": None})
    
#     # t = time.time()
#     # timestamp= int(round(t * 1000))    #毫秒级时间戳 
#     # file_path = bgimgPath+timestamp
#     # img.save(file_path) 

#     return jsonify({"code": 200,"status":True, "msg": "上传成功", "data": None})

 
 
# # Flask上传文件的实现 上传有问题
# @app.route('/upload/fff',methods=['POST'])
# def upload():
#     if request.method == 'GET':
#         return ""
#     else:
#         # 获取pichead文件对象
#         pichead = request.files.get('pichead')
#         print(request.files,"infose")
#         # 保存到服务器
#         # save方法传完整的路径和文件名
#         # pichead.save(os.path.join(UPLOAD_PATH,pichead.filename))
#         # 上行可以进行优化,下行是对pichead文件名进行包装，保证文件名更安全。  
#         pichead.save(os.path.join(bgimgPath,"ing.png"))
#         return ""


# Todo 主程序启动页面
if __name__=='__main__':
    # print(author)
    app.run(host=appsetting["host"], port=appsetting["port"],debug=appsetting["debug"])
    